//
//  CertificationView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/20.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class CertificationView: BaseView, UITableViewDataSource, UITableViewDelegate {
    var viewModel: CertificationViewModel?
    var selectIdentyStr = ""
    var nameText:BaseTextField?
    var selectText:BaseTextField?
    var numberText:BaseTextField?
    
    
    lazy var tableView:UITableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain)
    
    lazy var selectBtn:UIButton = {
        let btn =  CommonBtn.creatSelectBtnWithTitle(title: kText("确认"), y: 28, view: self, sel:  #selector(selectBtnAction))
        return btn
    }()

    override func setUpUI() -> Void {
        viewModel = dataSource as? CertificationViewModel
        if !(viewModel?.isChinese)! {
            selectIdentyStr = kText("护照")
            selectBtn.setTitle(kText("下一步"), for: UIControlState.normal)
        }else {
            selectIdentyStr = kText("大陆身份证")
        }
        
        self.addSubview(tableView)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.backgroundColor = UIColor.clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.top.equalToSuperview()
        }
        let footView = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 100))
        tableView.tableFooterView = footView

        footView.addSubview(selectBtn)
        selectBtn.isEnabled = false
        CommonBtn.createImageWithColor(color: kDisableColor, btn: selectBtn, state: UIControlState.normal)
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = viewModel?.cellfactory.cellIdentiferAtIndexPath(indexPath)
        let item = viewModel?.cellfactory.itemAtIndexPath(indexPath)
        var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier!) as? BaseTableViewCell
        if cell == nil {
            switch item!.type! {
            case .cyNameWrite:
                cell = NameWriteCell(style: .default, reuseIdentifier:cellIdentifier)
                break
            case .cySelectType:
                cell = SelectNameCell(style: .default, reuseIdentifier:cellIdentifier)
                break
            default : break
            }
            cell?.tag = indexPath.row
            cell?.selectionStyle = .none
            let styleCell = (cell as? NameWriteCell)
            if styleCell != nil {
                styleCell?.textField.snp.updateConstraints { (make) in
                    make.left.equalToSuperview().offset(15)
                }
                styleCell?.identyTextField.snp.updateConstraints({ (make) in
                    make.left.equalToSuperview().offset(15)
                })
            }
        }
        
        switch item!.type! {
        case .cyNameWrite:
            let cell = (cell as! NameWriteCell)
            if indexPath.row == 0 {
                cell.textField.textDelegate = self
                cell.identyTextField.textDelegate = self
                cell.textField.isHidden = false
                cell.identyTextField.isHidden = true
                nameText = cell.textField
                cell.textField.text = viewModel?.name
            }else {
                cell.textField.isHidden = true
                numberText = cell.identyTextField
                cell.identyTextField.isHidden = false
                cell.identyTextField.text = viewModel?.idCard
                if selectIdentyStr == kText("大陆身份证") {
                    item?.placeHolder = kText("请输入身份证号码")
                    cell.identyTextField.isOpenIdentyKeyBoard = true
                }else if selectIdentyStr == kText("护照"){
                    item?.placeHolder = kText("请输入护照号码")
                     cell.identyTextField.isOpenIdentyKeyBoard = false
                }else {
                    item?.placeHolder = kText("请输入证件号码")
                    cell.identyTextField.isOpenIdentyKeyBoard = false
                }
            }
            cell.identyTextField.textDelegate = self
            cell.setIteam(item!)
            break
        case .cySelectType:
            let cell = (cell as! SelectNameCell)
            cell.nameLabel.text = selectIdentyStr.count != 0 ?  selectIdentyStr : kText("请选择证件类型")
            cell.changeColor(isHaveContent:selectIdentyStr.count != 0 ? true : false)
            break
        
        default : break
        }
        
        
        return cell!
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 53
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view:UIView = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 50))
        view.themeBackground = ThemeManager.ThemeColorKeys.background
        let titleLabel = BaseLabel(style: .twiceStyle)
        titleLabel.numberOfLines = 0
        titleLabel.font = UIFont.systemFont(ofSize: 12)
        titleLabel.text = kText("请确认是您本人，审核通过后不可修改。")
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
        }
        return view
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.endEditing(true)
         tableView.deselectRow(at: indexPath, animated: false)
    }

    @objc func selectBtnAction() -> Void {
        self.endEditing(true)
        if selectIdentyStr.count == 0 {
            CYMBShow.showMessage(kText("请选择证件类型"))
            return
        }
        if selectIdentyStr == kText("大陆身份证") {
        if !(viewModel?.idCard.isTrueIDNumber())!{
            CYMBShow.showMessage(kText("请输入正确的身份证号码"))
            return
        }
        }
        
        viewModel?.selectIdentyStr = selectIdentyStr
        if (viewModel?.isChinese)! {
        viewModel?.sendInformation()
        }else {
            let controller = CertifiPhotoViewController()
            controller.viewModel?.isChinese = (viewModel?.isChinese)!
            controller.viewModel?.name = (viewModel?.name)!
            controller.viewModel?.idCard = (viewModel?.idCard)!
            controller.viewModel?.country = (viewModel?.country)!
            self.viewModel?.controller?.navigationController?.pushViewController(controller, animated: false)
        }
    }
    
    func changeStates()  {
       
        if viewModel?.name.ch_length != 0 && viewModel?.idCard.ch_length != 0
        {
            selectBtn.isEnabled = true
            CommonBtn.createImageWithColor(color:kThemeColor, btn: selectBtn, state: UIControlState.normal)
        }else {
            selectBtn.isEnabled = false
            CommonBtn.createImageWithColor(color: kDisableColor, btn: selectBtn, state: UIControlState.normal)
        }
        
    }
    
//    /// SlecterProcotol
//    ///
//    /// - Parameter selecterStr:
//    func selectData(selecterStr: String) {
//        identyCell?.nameLabel.text = selecterStr
//    }
//    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
extension CertificationView:BaseTextFieldDelegate, SelectmangerDelegate{
    
    
    func textFieldDidChange(textField: BaseTextField) {
        if textField == nameText {
            viewModel?.name = textField.text!
        }
        if textField == numberText {
            self.viewModel?.idCard = textField.text!
        }
        
        self.changeStates()
    }
    
    //MARK: -- SelectmangerDelegate
    func selectModel(model: SheetModel) {
        selectIdentyStr = model.selectStr!
        viewModel?.idCard = ""
        tableView.reloadData()
    }
    
    
}
